package handlers

import (
	"errors"
	"fmt"
	"net/http"

	"github.com/gin-gonic/gin"
	"swu.com/80p/internal/dbs"
)

// 创建记录接口的 Gin Handler
func CreateHandler(c *gin.Context) {
	db := dbs.GetDB()

	tableName := c.Param("tableName")
	if tableName == "" {
		c.JSON(http.StatusBadRequest, getGinError(errors.New("table name is required")))
		return
	}

	var data map[string]interface{}
	if err := c.ShouldBindJSON(&data); err != nil {
		c.JSON(http.StatusBadRequest, getGinError(err))
		return
	}

	result := db.Table(tableName).Create(&data)
	if result.Error != nil {
		c.JSON(http.StatusInternalServerError, getGinError(fmt.Errorf("database error: %v", result.Error)))
		return
	}

	c.JSON(http.StatusCreated, getGinResult(data)) // 返回创建后的数据，通常包含自增 ID
}
